<template>
  <n-modal
    :show="props.visible"
    preset="card"
    :title="'修改头像'"
    style="width: 800px"
    @after-enter="handleOpen"
    @close="handleClose"
  >
    <n-grid cols="2" :x-gap="30">
      <n-grid-item>
        <div class="h-[350px]">
          <VueCropper
            ref="cropperRef"
            mode="contain"
            moving="cropMoving"
            :full="false"
            :img="options.img"
            :info="true"
            :auto-crop="options.autoCrop"
            :auto-crop-width="options.autoCropWidth"
            :auto-crop-height="options.autoCropHeight"
            :fixed-box="options.fixedBox"
            :output-type="options.outputType"
            @real-time="handleRealTime"
          ></VueCropper>
        </div>
      </n-grid-item>
      <n-grid-item class="flex flex-col justify-center items-center">
        <div
          :style="{
            width: preview?.w + 'px',
            height: preview?.h + 'px',
            overflow: 'hidden',
            margin: '5px',
            border: '1px solid #e8e8e8',
            borderRadius: '50%',
          }"
        >
          <div :style="preview?.div">
            <img :src="preview?.url" :style="preview?.img" style="max-width: unset" alt="" />
          </div>
        </div>
      </n-grid-item>
    </n-grid>

    <template #footer>
      <div class="flex w-full justify-between">
        <n-space justify="start">
          <n-upload
            :headers="{
              'naive-info': 'hello!',
            }"
            :data="{
              'naive-data': 'cool! naive!',
            }"
            accept="image/*"
            @before-upload="handleBeforeUpload"
          >
            <n-button>
              <template #icon><CloudUploadOutlined /></template>上传图片
            </n-button>
          </n-upload>
          <n-button strong secondary circle type="primary" @click="changeScale(1)">
            <template #icon><PlusRound /></template>
          </n-button>
          <n-button strong secondary circle type="primary" @click="changeScale(-1)">
            <template #icon><HorizontalRuleTwotone /></template>
          </n-button>
          <n-button strong secondary circle type="primary" @click="rotateLeft">
            <template #icon><RotateLeftFilled /></template>
          </n-button>
          <n-button strong secondary circle type="primary" @click="rotateRight">
            <template #icon><RotateRightFilled /></template>
          </n-button>
        </n-space>
        <n-space justify="end">
          <n-button @click="handleClose">取消</n-button>
          <n-button type="primary" :loading="loading" @click="handleSubmitUpload"
            >确认上传</n-button
          >
        </n-space>
      </div>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { computed, reactive, ref, useTemplateRef } from 'vue';
import defaultAvatar from '@/assets/images/avatar.png';
import {
  CloudUploadOutlined,
  PlusRound,
  HorizontalRuleTwotone,
  RotateRightFilled,
  RotateLeftFilled,
} from '@vicons/material';
import { updateProfileAvatar } from '@/apis/system/user';
import { useMessage } from 'naive-ui';

const emits = defineEmits(['close']);
const props = defineProps<{ visible: boolean; data: any }>();
const data = computed<any>(() => props.data || {});
const loading = ref(false);
const message = useMessage();
const cropperRef = useTemplateRef<any>('cropperRef');
const preview = ref<any>(null);
const options = reactive({
  img: data.value?.avatar || defaultAvatar,
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 200, // 默认生成截图框宽度
  autoCropHeight: 200, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  outputType: 'png', // 默认生成截图为PNG格式
  filename: '', // 截图生成的文件名称
  centerBox: true,
  high: true,
});

// watch(
//   () => data.avatar,
//   (newVal) => {
//     options.img = newVal || defaultAvatar;
//   },
// );

function handleOpen() {}

function handleClose(needRefresh = false) {
  emits('close', { needRefresh });
}

function changeScale(num: number) {
  cropperRef.value.changeScale(num);
}

function rotateLeft() {
  cropperRef.value.rotateLeft();
}

function rotateRight() {
  cropperRef.value.rotateRight();
}

function handleRealTime(data: string) {
  console.log('实时裁剪图片base64', data);
  preview.value = data;
}

function handleBeforeUpload(data: any) {
  const { file } = data;

  const reader = new FileReader();
  reader.readAsDataURL(file.file);
  reader.onload = (e) => {
    options.img = e.target?.result;
    options.filename = file.name;
  };
  return false; // 阻止自动上传
}

function handleSubmitUpload() {
  cropperRef.value.getCropBlob(async (data: any) => {
    // TODO: 上传图片
    const formData = new FormData();
    formData.append('avatarfile', data, options.filename);
    loading.value = true;
    try {
      const res: any = await updateProfileAvatar(formData);
      if (res.code === 200) {
        handleClose(true);
        message.success('更新成功');
      }
    } catch (error) {
    } finally {
      loading.value = false;
    }
  });
}
</script>

<style lang="less" scoped></style>
